package middleware

import (
	"gin-zc/controller"
	"net/http"
	"strings"

	"gin-zc/config"
	"gin-zc/util"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1. 从Header获取Token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, controller.Error(401, "authorization header is required"))
			c.Abort() // 终止请求
			return
		}

		// 2. 检查Token格式（Bearer <token>）
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, controller.Error(401, "invalid authorization format"))
			c.Abort()
			return
		}

		// 3. 解析Token
		userID, err := util.ParseToken(parts[1], cfg)
		if err != nil {
			c.JSON(http.StatusUnauthorized, controller.Error(401, "invalid or expired token"))
			c.Abort()
			return
		}

		// 4. 将用户ID存入上下文，供后续接口使用
		c.Set("user_id", userID)
		c.Next() // 继续处理请求
	}
}
